<?php
/*
 * @Author: SunnyJ
 * @Date: 2021-05-07 14:06:26
 * @LastEditors: SunnyJ
 * @LastEditTime: 2021-06-02 11:51:05
 */
namespace app\api\controller;
use think\Db;
use app\service\OrderService;
use app\service\BuyService;
use app\service\MessageService;


class Order2 extends Base2 {

    /**
     * 预下订单接口
     * @description: 下单后锁定库存等资源，等待确认接口后再发货。所有订单默认开明细发票
     * @param { 授权接口获取的access token } $token
     * @param { 订单方平台code(id) } $platformCode
     * @param { 阳光公采商城的订单单号 } $yggc_order
     * @param {  } $sku
     * @param { 收货人 } $name
     * @param { int 一级地址 } $province
     * @param { int 二级地址 } $city
     * @param { int 三级地址 } $county
     * @param { string 详细地址 } $address
     * @param { 邮编 } $zip
     * @param { 座机号 (与mobile其中一个有值即可) } $phone
     * @param { 手机号 (与phone其中一个有值即可）} $mobile
     * @param { 非必须 邮箱 } $email
     * @param { 非必须 备注（少于100字）} $remark
     * @param { 非必须 采购单位名称 } $dep_name
     * @param { 发票抬头，个人或公司名称 } $invoice_title
     * @param { String 1普通发票;2增值税发票；3 电子发票；默认为普通发票 } $invoice_type
     * @param { 纳税人识别号 } $invoice_org_code
     * @param { 非必须 增值票收票人 备注：当invoice_type=2 且时则此字段必填 } $invoice_name
     * @param { 非必须 注册电话  备注：当invoice_type=2 且时则此字段必填 } $invoice_phone
     * @param { 非必须 开户银行 备注：当invoice_type=2 且时则此字段必填 } $invoice_bank
     * @param { 非必须 开户行帐号 备注：当invoice_type=2 且时则此字段必填 } $invoice_bank_code
     * @param { 非必须 注册地址 备注：当invoice_type=2 且时则此字段必填 } $invoice_address
     * @param { 非必须 收票联系电话 } $invoice_mobile
     * @param { 非必须 收票地址 } $invoice_receipt_address
     * @param { int 1：货到付款，2：集中支付， 3：在线支付， 4：支票 5：账期支付 6：先款后货 } $payment
     * @param { Decimal 订单金额（包含运费） } $order_price
     * @param { Decimal 运费 } $freight
     * @param { int 订单模式：1-协议价（默认）)；2-团购模式； 3-特惠模式; 4-阶梯价模式 } $mode
     * @return {*}
     */
    public function submit($token,$platformCode,$yggc_order,$sku,$name,$province,$city,$county,$address,$zip,$phone,$mobile,$email,$remark,$dep_name,$invoice_title,$invoice_type,$invoice_org_code,$invoice_name,$invoice_phone = '',$invoice_bank = '',$invoice_bank_code = '',$invoice_address = '',$invoice_mobile = '',$invoice_receipt_address,$payment,$order_price,$freight,$mode) {
        // 验证token与platformCode
        $auth = Auth2::check_token($token,$platformCode);
        if (!$auth['result']) {
            return $this -> create('', $auth['msg'], false);
        }
        // 清点货物
        $total_price = 0;
        $buy = array();
        // 把HTML字符串转回数组
        $sku = htmlspecialchars_decode($sku);
        $sku = json_decode($sku, true);
        foreach ($sku as &$s) {
            // 价格校验
            $p = Db::name('goods_spec_base')->where('id',$s['sku'])->find();
            if (empty($p)) {
                return $this -> create('', 'sku does not exist', false);
            }
            if ($p['price'] != $s['price']) {
                return $this -> create('', '价格不一致', false);
            }
            $total_price += $s['price'] * $s['num'];
            $buy[] = [
                'goods_id'          =>          $p['goods_id'],
                'num'               =>          $s['num'],
                'price'             =>          $p['price'],
                'original_price'    =>          $p['original_price'],
                'spec_weight'       =>          $p['weight'],
                'spec_coding'       =>          $p['coding'],
                'spec_barcode'      =>          $p['barcode']
            ];
        }
        // 下订单
        // 录入发票信息，可以加入订单流程

        // copied code
        // 进行一些基础设定
        // 用户id设为9999,需在数据库中加入
        $user_id = 9999;

        // 支付方式(线下支付)
        $payment_id = 1;
        $is_under_line = 1;

        // 订单主信息
        $order = [
            'order_no'              => date('YmdHis').GetNumberCode(6),
            'user_id'               => $user_id,
            'user_note'             => isset($remark) ? str_replace(['"', "'"], '', strip_tags($remark)) : '',
            'status'                => 0,
            'preferential_price'    => 0.00,
            'increase_price'        => 0.00,
            'price'                 => ($total_price <= 0.00) ? 0.00 : $total_price,
            'total_price'           => ($total_price <= 0.00) ? 0.00 : $total_price,
            'payment_id'            => $payment_id,
            'buy_number_count'      => array_sum(array_column($buy,'num')),
            'client_type'           => 'pc',
            'order_model'           => 0,  // 站点模式 0销售, 2自提, 4销售+自提
            'is_under_line'         => $is_under_line,
            'add_time'              => time(),
        ];
        if($order['status'] == 1)
        {
            $order['confirm_time'] = time();
        }

        // 开始事务
        Db::startTrans();

        // 订单添加
        $order_id = Db::name('Order')->insertGetId($order);
        if($order_id > 0)
        {
            foreach($buy as &$b)
            {
                // 订单详情数据
                $detail = Db::name('goods')->where('id',$b['goods_id'])->find();
                // 商品是否上架
                if ($detail['is_shelves'] == 0) {
                    return $this -> create('', "订单预约失败：商品({$detail['title']})已下架", false);
                }
                $data = [
                    'order_id'          => $order_id,
                    'user_id'           => $user_id,
                    'goods_id'          => $b['goods_id'],
                    'title'             => $detail['title'],
                    'images'            => $detail['images'],
                    'original_price'    => $b['original_price'],
                    'price'             => $b['price'],
                    'total_price'       => PriceNumberFormat($b['num']*$b['price']),
                    'spec'              => empty($detail['spec']) ? '' : json_encode($detail['spec']),
                    'spec_weight'       => empty($b['spec_weight']) ? 0.00 : (float) $b['spec_weight'],
                    'spec_coding'       => empty($b['spec_coding']) ? '' : $b['spec_coding'],
                    'spec_barcode'      => empty($b['spec_barcode']) ? '' : $b['spec_barcode'],
                    'buy_number'        => intval($b['num']),
                    'model'             => $detail['model'],
                    'add_time'          => time(),
                ];
                // 添加订单详情数据
                $order_detail_id = Db::name('OrderDetail')->insertGetId($data);
                if($order_detail_id <= 0)
                {
                    Db::rollback();
                    return $this -> create('', '订单详情添加失败', false);
                }
            }

            // 临时参数
            $province_name = Db::name('region')->where('id',$province)->value('name');
            $city_name = Db::name('region')->where('id',$city)->value('name');
            $county_name = Db::name('region')->where('id',$county)->value('name');
            // 订单收货地址
            $data = [
                'order_id'      => $order_id,
                'user_id'       => $user_id,
                'address_id'    => 1,
                'alias'         => '',
                'name'          => $name,
                'tel'           => isset($phone) ? $phone : $mobile,
                'province'      => $province,
                'city'          => $city,
                'county'        => $county,
                'address'       => isset($address) ? $address : '',
                'province_name' => empty($province_name) ? '未知省份' : $province_name,
                'city_name'     => empty($city_name) ? '未知城市' : $city_name,
                'county_name'   => empty($county_name) ? '未知县区' : $county_name,
                'lng'           => '0.0000000000',
                'lat'           => '0.0000000000',
                'add_time'      => time(),
            ];

            // 添加订单地址
            if(Db::name('OrderAddress')->insertGetId($data) <= 0)
            {
                Db::rollback();
                return $this -> create('','订单地址添加失败', false);
            }

            // 订单发票信息
            $data = [
                'order_id'          => $order_id,
                'skus'              => json_encode($sku),
                'invoice_type'      => $invoice_type,
                'title'             => $invoice_title,
                'org_code'          => $invoice_org_code,
                'name'              => $invoice_name,
                'phone'             => $invoice_phone,
                'bank'              => $invoice_bank,
                'bank_code'         => $invoice_bank_code,
                'address'           => $invoice_address,
                'mobile'            => $invoice_mobile,
                'receipt_address'   => $invoice_receipt_address,
                'invoice_dl_address'=> '',
                'add_time'          => time(),
            ];
            // 添加订单发票数据
            if(Db::name('order_invoice')->insertGetId($data) <= 0) {
                Db::rollback();
                return $this -> create('', '发票信息录入失败', false);
            }

        } else {
            Db::rollback();
            return $this -> create('', '订单生成失败', false);
        }

        // 库存扣除(不需要，确认订单才扣除库存)

        // 订单提交成功
        Db::commit();

        // 获取数据库订单信息
        $order = Db::name('Order')->find($order_id);

        // 获取订单信息
        if ($order['status'] == 0) {
            $result = [
                'mall_order_id'         =>      $order['order_no'],
                'sku'                   =>      $sku,
                'order_price'           =>      $order['total_price'],
                'freight'               =>      $freight,
            ];
            return $this -> create($result, '订单预约成功');
        }
    }

    /**
     * @description: 确认订单接口
     * @param {*} $token
     * @param {*} $platformCode
     * @param {*} $order_id
     * @return {*}
     */
    public function confirm($token,$platformCode,$order_id) {
        // 验证token与platformCode
        $auth = Auth2::check_token($token,$platformCode);
        if (!$auth['result']) {
            return $this -> create('', $auth['msg'], false);
        }

        // 获取订单信息
        $order = Db::name('order')->where('order_no',$order_id)->find();
        // 验证订单id
        if (empty($order)) {
            return $this -> create('', '订单id有误,资源不存在或已被删除', false);
        }
        if(!in_array($order['status'], [0]))
        {
            $status_text = lang('common_order_user_status')[$order['status']]['name'];
            return $this -> create('', '状态不可操作['.$status_text.']', false);
        }

        // 开启事务
        Db::startTrans();

        // 更新订单状态
        $upd_data = [
            'status'        => 1,
            'confirm_time'  => time(),
            'upd_time'      => time(),
        ];
        if(Db::name('Order')->where('order_no',$order_id)->update($upd_data))
        {
            // 库存扣除
            $ret = BuyService::OrderInventoryDeduct(['order_id'=> $order['id'], 'order_data'=>$upd_data]);
            if($ret['code'] != 0)
            {
                // 事务回滚
                Db::rollback();
                return $this->create('', $ret['msg'], false);
            }

            // 用户消息
            MessageService::MessageAdd($order['user_id'], '订单确认', '订单确认成功', 1, $order['id']);

            // 订单状态日志
            $creator = 0;
            $creator_name = '齐鲁云采';
            OrderService::OrderHistoryAdd($order['id'], $upd_data['status'], $order['status'], '确认', $creator, $creator_name);

            // 事务提交
            Db::commit();
            return $this -> create('','订单确认成功');
        }

        // 事务回滚
        Db::rollback();
        return $this -> create('', '订单确认失败', false);
    }

    /**
     * @description: 取消订单接口
     * @param {*} $token
     * @param {*} $platformCode
     * @param {*} $order_id
     * @return {*}
     */
    public function cancel($token,$platformCode,$order_id) {
        // 验证token与platformCode
        $auth = Auth2::check_token($token,$platformCode);
        if (!$auth['result']) {
            return $this -> create('', $auth['msg'], false);
        }

        // 获取订单信息
        $order = Db::name('order')->where('order_no',$order_id)->find();
        // 验证订单id
        if (empty($order)) {
            return $this -> create('', '订单id有误,资源不存在或已被删除', false);
        }
        if(!in_array($order['status'], [0,1]))
        {
            $status_text = lang('common_order_user_status')[$order['status']]['name'];
            return $this -> create('', '状态不可操作['.$status_text.']', false);
        }

        // 开启事务
        Db::startTrans();
        $upd_data = [
            'status'        => 5,
            'cancel_time'   => time(),
            'upd_time'      => time(),
        ];
        if(Db::name('order')->where('order_no',$order_id)->update($upd_data))
        {
            // 库存回滚
            $ret = BuyService::OrderInventoryRollback(['order_id'=>$order['id'], 'order_data'=>$upd_data]);
            if($ret['code'] != 0)
            {
                // 事务回滚
                Db::rollback();
                return $this -> create('', $ret['msg'], false);
            }

            // 用户消息
            MessageService::MessageAdd($order['user_id'], '订单取消', '订单取消成功', 1, $order['id']);

            // 订单状态日志
            $creator = 0;
            $creator_name = '齐鲁云采';
            OrderService::OrderHistoryAdd($order['id'], $upd_data['status'], $order['status'], '取消', $creator, $creator_name);

            // 提交事务
            Db::commit();
            return $this -> create('','订单取消成功');
        }

        // 事务回滚
        Db::rollback();
        return $this->create('', '订单取消失败', false);
    }

    /**
     * @description: 查询贵方订单信息接口
     * @param {*} $token
     * @param {*} $platformCode
     * @param {*} $order_id
     * @return {*}
     */
    public function select($token,$platformCode,$order_id) {
        // 验证token与platformCode
        $auth = Auth2::check_token($token,$platformCode);
        if (!$auth['result']) {
            return $this -> create('', $auth['msg'], false);
        }
        $order = Db::name('order')->where('order_no',$order_id)->find();
        if (!empty($order)) {
            $skus = Db::name('order_invoice')->where('order_id',$order['id'])->value('skus');
            $result = [
                'order_id'              =>      $order_id,
                'state'                 =>      in_array($order['status'],[0]) ? 0 : 1,
                'submit_state'          =>      in_array($order['status'],[0]) ? 0 : 1,
                'deliver_state'         =>      in_array($order['status'],[0,1,2,5]) ? 0 : 1,
                'total_price'           =>      $order['total_price'],
                'skus'                  =>      json_decode($skus, true),
                'return_skus'           =>      [],
            ];
            return $this -> create($result);
        }
        return $this -> create('', '订单查询失败，订单不存在', false);
    }

    /**
     * @description: 物流接口
     * @param {*} $token
     * @param {*} $platformCode
     * @param {*} $order_id
     * @return {*}
     */    
    public function track($token,$platformCode,$order_id) {
        // 验证token与platformCode
        $auth = Auth2::check_token($token,$platformCode);
        if (!$auth['result']) {
            return $this -> create('', $auth['msg'], false);
        }
        $order = Db::name('order')->where('order_no',$order_id)->find();
        if(!empty($order)) {
            if ($order['express_id'] != 0) {
                $express_info = Db::name('express')->where('id', $order['express_id'])->find();
                $skus = json_decode(Db::name('order_invoice')->where('order_id',$order['id'])->value('skus'), true);
                if (!empty($skus)) {
                    $shipment_items = [];
                    foreach ($skus as &$sku) {
                        $goods_id = Db::name('goods_spec_base')->where('id',$sku['sku'])->value('goods_id');
                        $name = Db::name('goods')->where('id',$goods_id)->value('title');
                        $shipment_items[] = [
                            'name'      =>      $name,
                            'num'       =>      $sku['num'],
                            'sku'       =>      $sku['sku'],
                        ];
                    }
                    $waybill = [
                        'order_id'              =>          $order_id,
                        'logistic_type'         =>          ($express_info['name'] == '自行送货') ? 1 : 2,// 1：供应商自行送货 2：快递 3：其他
                        'logistic_name'         =>          $express_info['name'],
                        'logistic_no'           =>          ($express_info['name'] == '自行送货') ? '' : $order['express_number'],
                        'shipment_id'           =>          ($express_info['name'] == '自行送货') ? '' : $order['express_number'],
                        'shipment_items'        =>          $shipment_items,
                    ];
                    $track = [];
                    $track[] = [
                        'content'               =>          '商家发货',
                        'operate_time'          =>          date("Y-m-d H:i:s",$order['delivery_time']),
                        'operater'              =>          '系统记录',
                    ];
                    if ($order['collect_time'] != 0) {
                        $track[] = [
                            'content'               =>          '买家收货',
                            'operate_time'          =>          date("Y-m-d H:i:s",$order['collect_time']),
                            'operater'              =>          '系统记录',
                        ];
                    }
                    $result = [
                        'track'           =>      $track,
                        'waybill'         =>      $waybill,
                    ];
                    return $this -> create($result);
                }
                return $this -> create('', '网页订单无法通过API查询物流信息', false);
            }
            return $this -> create('', '订单尚未发货，暂无物流信息', false);
        }
        return $this -> create('', '物流信息查询失败，订单或订单号不存在', false);
    }
}

?>